package com.carpedil.shirodemo.common.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IPUtils {

  /**
   * 获取请求 IP (WEB 服务)
   *
   * @return IP 地址
   */
  public static String getIpAddr() {
    HttpServletRequest request =
        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
      if (ip.equals("127.0.0.1")) {
        // 根据网卡取本机配置的 IP
        InetAddress inet = null;
        try {
          inet = InetAddress.getLocalHost();
          ip = inet.getHostAddress();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    // 多个代理的情况，第一个 IP 为客户端真实 IP,多个 IP 按照','分割
    if (ip != null && ip.length() > 15) {
      if (ip.indexOf(",") > 0) {
        ip = ip.substring(0, ip.indexOf(","));
      }
    }
    return ip;
  }

  /** 获取当前计算机 IP */
  public static String getHostIp() {
    try {
      return InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
    return "127.0.0.1";
  }

  /** 获取当前计算机名称 */
  public static String getHostName() {
    try {
      return InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
    return "未知";
  }
}
